package com.first.wchat.connect.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

import com.first.wchat.data.Constant;

import android.content.Context;
import android.util.Log;

public class UDPRecevier {
	
	DataReceiverListener mListener;
	public UDPRecevier()
	{
	}

	public void setListener(DataReceiverListener listener)
	{
		mListener = listener;
	}
	
	public void receive(final Context ctx)
	{
		
		new Thread(new Runnable()
		{

			@Override
			public void run() { 
				Integer port = Constant.PORT;  
		        byte[] message = new byte[1024];  
		        try {  
		            DatagramSocket datagramSocket = new DatagramSocket(port);  
		            DatagramPacket datagramPacket = new DatagramPacket(message,  
		                    message.length);  
		            try {  
		                while (true) {  

		                    datagramSocket.receive(datagramPacket);  
		                    String data =  "UDP receive =================From:"+datagramPacket.getAddress()  
                            .getHostAddress().toString()  
                            + " data:" + new String(datagramPacket.getData());
		                    
		                    if(mListener!=null)
		                    	mListener.receiver(datagramPacket.getAddress()  
			                            .getHostAddress().toString(),new String(datagramPacket.getData() ,"UTF-8"),null);
		                    
		                    
		                    
		                    Log.d("UDP receive =================", datagramPacket.getAddress()  
		                            .getHostAddress().toString()  
		                            + ":" + new String(datagramPacket.getData()));  
		                }  
		            } catch (IOException e) {  
		                e.printStackTrace();  
		                datagramSocket.close();
		            }  
		        } catch (SocketException e) {  
		            e.printStackTrace();  
		        } 	
			}
			
		}).start();
		
	}
	
}
